package com.thread.chapter3;

import cn.hutool.core.thread.ThreadUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class Demo3_1_1 extends Thread {

    private Demo3_1_1 task;

    //传参决定执行哪个方法
    private String execMethod = "";

    private List<String> list = new ArrayList<>();

    public void add() {
        list.add("元素");
    }

    public int size() {
        return list.size();
    }

    public Demo3_1_1(Demo3_1_1 task, String execMethod) {
        System.out.println("此时我是main线程调用构造方法:" + currentThread().getName());
        this.task = task;
        this.execMethod = execMethod;
    }

    public void methodA(String execMethod) {
        currentThread().setName(execMethod);
        System.out.println("线程--" + currentThread().getName() + "开始");
        for (int i = 0; i < 10; i++) {
            add(); //执行当前对象的方法，不是当前对象内的属性task的方法
            System.out.println("添加了" + (i + 1) + "个元素");
            ThreadUtil.sleep(1000);
        }
        System.out.println("syncMethodA 结束:" + currentThread().getName());
    }

    public void methodB(String execMethod) {
        currentThread().setName(execMethod);
        System.out.println("线程--" + currentThread().getName() + "开始");
        while (true) {
            ThreadUtil.sleep(1000);
            if (size() > 5) {
                System.out.println("元素个数==5,线程" + currentThread().getName() + "要退出了");
                try {
                    throw new InterruptedException();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void run() {
        super.run();
        if ("A".equals(execMethod)) {
            task.methodA(execMethod);
        } else if ("B".equals(execMethod)) {
            task.methodB(execMethod);
        }
    }

    public static void main(String[] args) {
        //两个不同的线程对象a和b调用同一个对象task的方法
        //线程b通过while循环不停检测条件造成cpu的浪费
        Demo3_1_1 task = new Demo3_1_1();
        Demo3_1_1 a = new Demo3_1_1(task, "A");
        a.start();
        Demo3_1_1 b = new Demo3_1_1(task, "B");
        b.start();

    }
}
